<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    refreshResetToken();
    require("reset_form.php");
    exit();
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['reset_token']) || $_POST['reset_token'] != $_SESSION['reset_token']) {
        fail("Invalid reset token!");
    }
    refreshResetToken();

    include_once("auth_process.php");
    $email = $_POST['email'];

    require_once("validator.php");
    if (!validateEmail($email)) {
        fail("Invalid email pattern");
    }

    $user = getUserByEmail($email);

    if ($user == null) {
        fail("No such email !");
    } else {
        include_once("email_sender.php");
        $conn = getdb();
        $link = createResetRecord($conn, $email);
        sendResetPasswordEmail($email, $link);

        echo "<script>alert(\"Reset email will send to your mailbox, please follow the link to reset your password.\"); window.location.href=\"index.php\"</script>";
    }
}

function fail($msg)
{
    echo "<script>alert(\"Reset request fail ! {$msg}\"); window.location.href=\"reset_password.php\"</script>";
    exit();
}

function refreshResetToken(){
    $reset_token = md5(time() . "reset_token" . rand(0, 9999));
    $_SESSION['reset_token'] = $reset_token;
}

function createResetRecord($conn, $email)
{
    $stmt = $conn->prepare("UPDATE resets SET active=0 WHERE email=:email");
    $stmt->bindParam(':email', $email);
    $stmt->execute();

    $reset_nonce = md5(time() . "reset_token" . rand(0, 9999));
    $stmt = $conn->prepare("INSERT INTO resets(email, nonce, active) VALUES (:email,:nonce,'1')");
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':nonce', $reset_nonce);
    $stmt->execute();

    $link = "https://secure.s3.ierg4210.ie.cuhk.edu.hk/phps/reset_handler.php?email=" . urlencode($email) . "&nonce=" . urlencode($reset_nonce);

    return $link;
}

